/*
 * @Author: xiehangyun 
 * @Date: 2025-05-15 10:30:12 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-14 16:28:21
 */

import { autorun, makeAutoObservable, toJS } from "mobx";
import shoppingCartApi from "./shoppingCartApi";
import { GoodsData, ShopCarData } from "types/type";
import userStore from "../User/userStore";
import Taro from "@tarojs/taro";
import { isEmpty, isString } from "lodash";

//购物车
class ShoppingCartStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });

        autorun(() => {
            if (userStore.isLogin) {
                this.getList();
            }
        });

    }

    page: number = 1;//当前页面
    pageSize: number = 999999;//分页数
    total: number = 0;//总数
    list: Array<ShopCarData> = [];//数据列表
    setList(list: Array<ShopCarData>) {
        this.list = list;
    }
    hasMore: boolean = true;//是否有更多数据
    totalPrice: number = 0; //总价

    loadding = true; //列表是否正在请求中
    //获取数据
    async getList(page: number = this.page, pageSize: number = this.pageSize) {
        this.loadding = true;
        this.page = page;
        this.pageSize = pageSize;
        await shoppingCartApi.getList(page, pageSize).then(res => {
            res.rows.forEach(item => {
                if (isString(item.productDesign)) {
                    item.productDesign = JSON.parse(item.productDesign);
                }
            });
            this.setList(res.rows);
            this.total = res.total;
            this.hasMore = (res.rows.length === this.pageSize);
            this.setSelectedItemIds([...this.selectedItemIds]);
        }).catch(err => {
            console.log(err);
        });
        this.loadding = false;
    }

    selectedItemIds: Array<number> = [];//选中的商品id
    setSelectedItemIds(selectedItemIds: Array<number>) {
        this.selectedItemIds = [...selectedItemIds.filter(selectedItemId => this.list.some(item => selectedItemId === item.id))];

        if (isEmpty(selectedItemIds)) {
            this.totalPrice = 0;
        } else {
            shoppingCartApi.caculateProductPrice(selectedItemIds.join(","))
                .then(res => {
                    this.totalPrice = res.data || 0;
                })
                .catch(err => {
                    console.log(err);
                })
        }
    }

    //取消全部选中
    cancelAllSelect() {
        this.selectedItemIds = [];
    }

    // 添加购物车
    add(shopCarData: {
        productId: number, // 商品id
        productNegativeId: number, // 底板id
        designName: string,
        productDesign: GoodsData["productData"],// 具体商品设计json
        productShowImageUrl: string, // 商品图片
        size: string, // 规格
        color?: string // 颜色
        addToDesign: boolean, // 是否添加到设计
    }) {
        return shoppingCartApi.add(shopCarData).then(res => {
            this.getList();
        });
    }

    //编辑
    edit(shopCarData: ShopCarData) {
        return shoppingCartApi.edit(shopCarData).then(res => {

            this.getList();
        });
    }

    // 修改购物车商品的数量
    changeProductNumber(shopCartId: number, productNumber: number) {
        return shoppingCartApi.changeProductNumber(shopCartId, productNumber).then(res => {
            this.getList();
        });
    }


    // 修改购物车商品规格
    changeProductSize(shopCartId: number, productSize: string) {
        return shoppingCartApi.changeProductSize(shopCartId, productSize).then(res => {
            this.getList();
        });
    }

    // 删除购物车商品
    delete(shopCartIds: string) {
        return shoppingCartApi.delete(shopCartIds).then(res => {
            let selectedItemIds = toJS(this.selectedItemIds);
            selectedItemIds = selectedItemIds.filter(item => shopCartIds.includes(item.toString()));
            this.setSelectedItemIds(selectedItemIds);
            this.getList();
        });
    }

    // 复制购物车
    copyShopCart(shopCartId: number) {
        return shoppingCartApi.copyShopCart(shopCartId).then(res => {
            this.getList();
            Taro.showToast({ title: "复制成功" });
        });
    }

}

const shoppingCartStore = new ShoppingCartStore();

export default shoppingCartStore;